﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using System.Data.Services.Client;
using Social_Photos.Social_Photos_Services;
using System.IO;
using System.Net;
using System.Text;
namespace Social_Photos
{
    public partial class PhotoDetails : PhoneApplicationPage
    {
        private Photo currentPhoto;
        int index;
        int id;
        string comment;
        int _like;
        int _dislike;
        string flag;
        
        // Set the string of your streaming service implementation.
        static string serviceUriString = UrlConfig.SERVICE_URI_STRING;

        // Declare the service root URI.
        private Uri svcRootUri =
            new Uri(serviceUriString, UriKind.Absolute);

        // Declare our private binding collection.
        private DataServiceCollection<Photo> _photos;
        private DataServiceCollection<Comment> _comments;

        // Declare the DataServiceContext as private.
        private SocialPhotoModelContainer _context;
        string latitude;
        string longitude;

        public PhotoDetails()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            
            //// Get the selected PhotoInfo object.
            string filename = this.NavigationContext.QueryString["filename"];
            string idAsString = this.NavigationContext.QueryString["Id"];
            string like = this.NavigationContext.QueryString["like"];
            string dislike = this.NavigationContext.QueryString["dislike"];
            latitude = this.NavigationContext.QueryString["latitude"];
            longitude = this.NavigationContext.QueryString["longitude"];

            tblike.Text = like;
            tbdislike.Text = dislike;

            id = int.Parse(idAsString);
            _like = int.Parse(like);
            _dislike = int.Parse(dislike);

            Uri uri = new Uri(UrlConfig.GET_URL_PHOTO + filename);
            BitmapImage bmp = new BitmapImage(uri);
            PhotoImage.Source = bmp;
        }


        private void like_Click(object sender, EventArgs e)
        {    //Margin="6,12,6,300">

            flag = "like";
            _context = new SocialPhotoModelContainer(svcRootUri);
            _photos = new DataServiceCollection<Photo>(_context);
           
            // Load the data from the PhotoInfo feed.
            _photos.LoadAsync(new Uri(UrlConfig.LIKE_SERVICE_STRING +id, UriKind.Relative));

            // Register for the LoadCompleted event to turn off the progress bar.
            _photos.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(Photos_LoadCompleted);
           
        
        }


        private void dislike_Click(object sender, EventArgs e)
        {
            flag = "dislike";
            _context = new SocialPhotoModelContainer(svcRootUri);
            _photos = new DataServiceCollection<Photo>(_context);

            // Load the data from the PhotoInfo feed.
            _photos.LoadAsync(new Uri(UrlConfig.DISLIKE_SERVICE_STRING + id, UriKind.Relative));

            // Register for the LoadCompleted event to turn off the progress bar.
            _photos.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(Photos_LoadCompleted);
            
        }


        private void Photos_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                // Make sure that we load all pages of the Customers feed.
                if (_photos.Continuation != null)
                {
                    // Request the next page from the data service.
                    _photos.LoadNextPartialSetAsync();
                }
                else
                {
                    if (flag == "like")
                    {
                        _like++;
                        tblike.Text = _like.ToString();                   
                    }else if (flag == "dislike")
                    {
                       _dislike++;
                       tbdislike.Text = _dislike.ToString();
                    }
                }
            }
            else
            {
                if (MessageBox.Show(e.Error.Message, "Retry request?",
                    MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    //    this.LoadData();
                }
            }
        }

        private void post_Click(object sender, EventArgs e)
        {

            this.PhotoImage.Height = 500;
            this.PhotoImage.Width = 300;
            VerticalAlignment v = new VerticalAlignment();
            HorizontalAlignment h = new HorizontalAlignment();

            this.PhotoImage.HorizontalAlignment = h;
            this.PhotoImage.VerticalAlignment = v;
            myComment.Visibility = System.Windows.Visibility.Visible;
          //  like_dislike.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void send_Click(object sender, RoutedEventArgs e)
        {
            comment = txtComment.Text;
            string post_comment_url = UrlConfig.POST_COMMENT;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(post_comment_url);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";
            request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
            txtComment.Text = String.Empty;
            //like_dislike.Visibility = System.Windows.Visibility.Visible;
            
        }

        private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
        {
            try
            {
               
                HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
              //  string encoding = "iso-8859-1";

                Stream postStream = request.EndGetRequestStream(asynchronousResult);
                string postData = string.Format("userID={0}&photoId={1}&comment={2}", 4, id, comment);
                byte[] bytePostData = Encoding.UTF8.GetBytes(postData);

                // Write to the request stream. 
                postStream.Write(bytePostData, 0, bytePostData.Length);
                postStream.Close();

                // Start the asynchronous operation to get the response 
                request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        private void GetResponseCallback(IAsyncResult asynchronousResult)
        {
            try
            {

                HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
                // End the operation 
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
                Stream streamResponse = response.GetResponseStream();
                StreamReader streamRead = new StreamReader(streamResponse);
                string responseString = streamRead.ReadToEnd();

                // Close the stream object 
                streamResponse.Close();
                streamRead.Close();
                response.Close();
            }
            catch (Exception ex)
            {

            }
        }

        private void location_Click(object sender, EventArgs e)
        {
           // latitude = "21.0254861";
            //longtitude = "105.853486";
            NavigationService.Navigate(new Uri("/GoogleMap.xaml?latitude="
                       + latitude + "&longtitude=" + longitude, UriKind.Relative));
        }

        /*------------------------------------------GESTURE---------------------------------------------*/
        double initialAngle;
        double initialScale;

        private void OnTap(object sender, GestureEventArgs e)
        {
            transform.TranslateX = transform.TranslateY = 0;
        }

        private void OnDoubleTap(object sender, GestureEventArgs e)
        {
            transform.ScaleX = transform.ScaleY = 1;
        }

        private void OnHold(object sender, GestureEventArgs e)
        {
            transform.TranslateX = transform.TranslateY = 0;
            transform.ScaleX = transform.ScaleY = 1;
            transform.Rotation = 0;
        }

        private void OnDragStarted(object sender, DragStartedGestureEventArgs e)
        {

        }

        private void OnDragDelta(object sender, DragDeltaGestureEventArgs e)
        {
            transform.TranslateX += e.HorizontalChange;
            transform.TranslateY += e.VerticalChange;
        }

        private void OnDragCompleted(object sender, DragCompletedGestureEventArgs e)
        {

        }

        private void OnPinchStarted(object sender, PinchStartedGestureEventArgs e)
        {


         //   initialAngle = transform.Rotation;
            initialScale = transform.ScaleX;
        }

        private void OnPinchDelta(object sender, PinchGestureEventArgs e)
        {
           // transform.Rotation = initialAngle + e.TotalAngleDelta;
            transform.ScaleX = transform.ScaleY = initialScale * e.DistanceRatio;
        }

        private void OnPinchCompleted(object sender, PinchGestureEventArgs e)
        {

        }

    }
}